package android.theHead;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.Handler;
import android.telephony.TelephonyManager;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.Toast;

public class patDebug extends Activity{
	
	Activity thisContext = this;
	
	public Handler handler = null;
	public Runnable runnable = null;

	private ComponentName service = null;
	
	public HeadLocationReceiver receiver = null;
	
	@Override
	public void onCreate(Bundle icicle) {
		super.onCreate(icicle);	
		setContentView(R.layout.pat_debug);
		
		Button postButton = (Button)findViewById(R.id.postButton);
		postButton.setOnClickListener(new View.OnClickListener(){
        	public void onClick(View v){
//        		String content = ((EditText) findViewById(R.id.EditText01)).getText().toString();
//        		((TextView) findViewById(R.id.text01)).setText(content);
        		Log.i("post","start!");
        		post();
        		Log.i("post","end!");
        	}
        });
		
		Button gpsButton = (Button)findViewById(R.id.gpsButton);
		gpsButton.setOnClickListener(new View.OnClickListener(){
        	public void onClick(View v){
        		Log.i("gps","start!");

        		// Acquire a reference to the system Location Manager
        		LocationManager locationManager = (LocationManager) thisContext.getSystemService(Context.LOCATION_SERVICE);

        		// Define a listener that responds to location updates
        		LocationListener locationListener = new LocationListener() {
        			public void onLocationChanged(Location location) {
        		      // Called when a new location is found by the network location provider.
        		      TextView gpstextView = (TextView) thisContext.findViewById(R.id.gpsTextView);
        		      gpstextView.setText(location.getLatitude() + " : " + location.getLongitude());
        		      
        		      HeadDBAdapter headDb = new HeadDBAdapter(thisContext);
        		      headDb.open();
        		      
    		    	  HeadReadings entry = new HeadReadings(location);
        		      
    		    	  // if there is already a DB entry get the distance to the last entry
        		      HeadReadings lastEntry = headDb.getLastEntry();
        		      if (lastEntry!=null){
        		    	  Location lastLocation = lastEntry.getLocation();
        		    	  entry.distance = location.distanceTo(lastLocation);
        		      } else {
        		    	  entry.distance = 0;
        		      }
        		      
        		      headDb.insertEntry(entry);
        		      headDb.close();
        		    }

        		    public void onStatusChanged(String provider, int status, Bundle extras) {}

        		    public void onProviderEnabled(String provider) {}

        		    public void onProviderDisabled(String provider) {}
        		  };

        		// Register the listener with the Location Manager to receive location updates
        		locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locationListener);

        		Log.i("gps","end!");
        	}
        });
		
		Button dbButton = (Button)findViewById(R.id.dbButton);
		dbButton.setOnClickListener(new View.OnClickListener(){
        	public void onClick(View v){
//        		String content = ((EditText) findViewById(R.id.EditText01)).getText().toString();
//        		((TextView) findViewById(R.id.text01)).setText(content);
        		Log.i("DB","start!");
        		testDB();
        		Log.i("DB","end!");
        	}
        });
		
		Button dbSubmit = (Button)findViewById(R.id.dbSubmit);
		dbSubmit.setOnClickListener(new View.OnClickListener(){
			public void onClick(View v){
				submitData();
			}
		});
		
		Button startService = (Button)findViewById(R.id.serviceStartButton);
		startService.setOnClickListener(new View.OnClickListener(){
			public void onClick(View v){
				startService();
			}
		});
		
		Button stopService = (Button)findViewById(R.id.serviceStopButton);
		stopService.setOnClickListener(new View.OnClickListener(){
			public void onClick(View v){
				stopService();
			}
		});
		
		Button stopService2 = (Button)findViewById(R.id.serviceStopButton2);
		stopService2.setOnClickListener(new View.OnClickListener(){
			public void onClick(View v){
				stopService2();
			}
		});
		
		Button startListView = (Button)findViewById(R.id.startListView);
		startListView.setOnClickListener(new View.OnClickListener(){
			public void onClick(View v){
				startListView();
			}
		});
		
		Button startTeamDB = (Button)findViewById(R.id.startTeamDB);
		startTeamDB.setOnClickListener(new View.OnClickListener(){
			public void onClick(View v){
				startTeamDB();
			}
		});
	}

	@Override
	protected void onPause() {
		super.onPause();
		unregisterReceiver(receiver); super.onPause();
		Log.i("patDebug", "onPause");
	}

	protected void onStop(){
		super.onStop();
		Log.i("patDebug", "onStop");
	}
	
	public void onResume(){
		super.onResume();
		Log.i("patDebug","onResume");
		IntentFilter filter;
		filter = new IntentFilter(BackgroundService.NEW_HEAD_READINGS);
		receiver = new HeadLocationReceiver();
		registerReceiver(receiver, filter);
	}
	
	public void onDestroy(){
		super.onDestroy();
		Log.i("patDebug", "onDestroy");
		if (service != null){
			try {
				Class serviceClass = Class.forName(service.getClassName());
				this.	stopService(new Intent(this, serviceClass));
			} catch (ClassNotFoundException e) {}
		}
	}
	
	public void post(){
    	PostData poster = new PostData();
    	JSONArray JArray  = null;
    	try {
    		JArray = new JSONArray().put(new JSONObject().put("id", "12345")).put(new JSONObject().put("id", "67890"));
            Log.i("post", JArray.toString());
    	} catch (JSONException e) {
    		e.printStackTrace();
    	}

        
        List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
        nameValuePairs.add(new BasicNameValuePair("data", JArray.toString()));
        nameValuePairs.add(new BasicNameValuePair("time", "now"));
        
        String result = poster.connect("http://pmast.de/rowTracker/testService.php", nameValuePairs);
        ((TextView) findViewById(R.id.text01)).setText(result);
        
    }	
	
	public void testDB(){
		Log.i("DB", "in testDB");
		HeadDBAdapter headDb = new HeadDBAdapter(thisContext);
		headDb.open();
		

		HeadReadings lastEntry = headDb.getLastEntry();
		if (lastEntry!=null){
			Log.i("DB", Double.toString(lastEntry.utcTime));
			((TextView) findViewById(R.id.dbTextView)).setText(lastEntry.toString());
		} else {
			Log.i("DB", "null");
			((TextView) findViewById(R.id.dbTextView)).setText("null");
		}
		headDb.close();

	}	
	
	public void submitData(){
		Log.i("DB", "in testDB");
		HeadDBAdapter headDb = new HeadDBAdapter(thisContext);
		headDb.open();
		JSONArray jArray = headDb.getUnsentEntries();
		headDb.close();
		TelephonyManager telephonyManager = (TelephonyManager)getSystemService(Context.TELEPHONY_SERVICE);
		
	    Date now = new Date();
	    long deviceTime = now.getTime();
		
		List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
        nameValuePairs.add(new BasicNameValuePair("data", jArray.toString()));
        nameValuePairs.add(new BasicNameValuePair("debiceID", telephonyManager.getDeviceId()));
        nameValuePairs.add(new BasicNameValuePair("deviceTime", Long.toString(deviceTime)));
        
        PostData poster = new PostData();
        
        String result = poster.connect("http://pmast.de/rowTracker/testService.php", nameValuePairs);

        try {
        	JSONObject jsonO = new JSONObject(result);
            if (jsonO.has("status") && jsonO.getInt("status")==1){
            	((TextView) findViewById(R.id.dbTextView)).setText("jeah!");
            } else {
            	((TextView) findViewById(R.id.dbTextView)).setText("oh no!");
            }
        } catch (JSONException e) {
    		e.printStackTrace();
    	}
        
	}
	
	public void startService(){
		(Toast.makeText(getApplicationContext(), "blah, blah!", Toast.LENGTH_SHORT)).show();
		service = this.startService(new Intent(this, BackgroundService.class));
	}
	
	public void stopService(){
		if (service != null){
			(Toast.makeText(getApplicationContext(), "trying to stop!", Toast.LENGTH_SHORT)).show();
			try {
				Class serviceClass = Class.forName(service.getClassName());
				this.stopService(new Intent(this, serviceClass));
			} catch (ClassNotFoundException e) {}
		}
	}
	
	public void stopService2(){
		if (service != null){
				this.stopService(new Intent(this, BackgroundService.class));
		}
	}
	
	public void startListView(){
		// create an explicit intent to call the patDebug activity
		Intent anIntent = new Intent(this, CurrentReadings.class);
		// start activity with the Intent
		this.startActivity(anIntent);		
	}
	
	
	public void startTeamDB(){
		TeamDBAdapter db = new TeamDBAdapter(thisContext);
		db.open();
		db.updateTeamInfo();
		db.close();
	}
	
	public class HeadLocationReceiver extends BroadcastReceiver {
		@Override
		public void onReceive(Context context, Intent intent) {
			HeadReadings headLocation = intent.getParcelableExtra(BackgroundService.HEAD_READINGS_FIELD);
			((TextView) findViewById(R.id.serviceTextView)).setText("distance: " + headLocation.distance);
		}
	}
	
}
